<template>
  <div class="share">
    <van-popup v-model="isShow" @close="popupClose">
      <div v-if="!resultBase64" class="share-wrapper">
        <!-- <div class="share-wrapper"> -->
        <div id="share-productV2">
          <div class="banner">
            <div class="goods_info_bg">
              <img src="../../assets/poster/goods_info_bg.png" />
            </div>
            <div class="goods-info">
              <div
                class="goods-meta-wrap"
                :style="{
                  left: +shareObj.xcoordinates / 2 + 'px',
                  top: +shareObj.ycoordinates / 2 + 'px'
                }"
              >
                <div class="goods-meta">
                  <!-- 10 活动， 20 商品-->
                  <span v-if="shareObj.shareBizType === 10"
                    >{{ shareObj.onlineProductCount }}款</span
                  >
                  <span v-for="(it, idx) in shareObj.coupons" :key="idx">
                    {{ it.thresholdAmount }}减{{ it.amount }}
                  </span>
                  <span
                    v-if="!shareObj.coupons || shareObj.coupons.length === 0"
                    >品质保障</span
                  >
                </div>
              </div>
              <img class="poster-img" :src="shareFloorImgUrl" />
            </div>
            <div class="activity-info">
              <span
                v-if="
                  shareObj.shareBizType === 10 &&
                    shareObj.activityLabelMap &&
                    shareObj.activityLabelMap.realSelfBusiness === 1
                "
                class="activity-label1"
              >
                <img src="../../assets/poster/label.png" />
              </span>
              <span
                v-if="
                  shareObj.shareBizType === 10 &&
                    shareObj.crossBorderProduct === 1
                "
                class="activity-label2"
              >
                <img src="../../assets/poster/label1.png" />
              </span>

              <span v-if="shareObj.productLabel === 1" class="activity-label1">
                <img src="../../assets/poster/label.png" />
              </span>
              <span
                v-else-if="shareObj.productLabel === 2"
                class="activity-label2"
              >
                <img src="../../assets/poster/label1.png" />
              </span>
              <span
                v-else-if="shareObj.productLabel === 4"
                class="activity-label4"
              >
                <img src="../../assets/poster/label2.png" />
              </span>
              <span
                v-else-if="shareObj.productLabel === 5"
                class="activity-label5"
              >
                <img src="../../assets/poster/label3.png" />
              </span>
              <p
                v-if="
                  (shareObj.scheduleType === 1 ||
                    shareObj.scheduleType === 2) &&
                    shareObj.status === 2
                "
                class="xianshitemai"
              >
                <img src="../../assets/poster/activity1.png" />
                <span>{{ shareObj.endTime }} 结束</span>
              </p>
              <p
                v-else-if="
                  (shareObj.scheduleType === 1 ||
                    shareObj.scheduleType === 2) &&
                    shareObj.status === 1
                "
                class="yugao"
              >
                <img src="../../assets/poster/activity2.png" />
                <span>{{ shareObj.beginTime }} 开始</span>
              </p>
              <p
                v-else-if="shareObj.scheduleType === 3 && shareObj.status === 2"
                class="jingxingzhong"
              >
                <img src="../../assets/poster/activity3.png" />
                <span>价格以实际购买为准</span>
              </p>
            </div>
          </div>
          <div class="shop-wrap">
            <div class="left-box">
              <div class="shop-info">
                <div class="shop-logo">
                  <img :src="forwarderShopLogoUrl || defaultImg" alt="" />
                </div>
                <div class="shop-desc">
                  <span
                    v-if="
                      shareObj.forwarder && shareObj.forwarder.forwarderMessage
                    "
                    >{{
                      (shareObj.forwarder &&
                        shareObj.forwarder.forwarderMessage) ||
                        '' | sliceHandle(19)
                    }}</span
                  >
                  <span>{{
                    (shareObj.forwarder &&
                      shareObj.forwarder.forwarderShopName) ||
                      '' | sliceHandle(8)
                  }}</span>
                  <span>{{
                    (shareObj.forwarder &&
                      shareObj.forwarder.forwarderShopDesc) ||
                      '' | sliceHandle(12)
                  }}</span>
                </div>
              </div>
              <div class="shop-meta">
                <span v-for="(it, idx) in shareObj.activityLabels" :key="idx">
                  <i>
                    <img src="../../assets/poster/gouxuan.png" alt="" />
                  </i>
                  <em>{{ it.labelName }}</em>
                </span>
              </div>
            </div>
            <div class="shop-link">
              <img class="qrcode poster-img" :src="qrcode" />
              <div class="qrcode-tip">
                <span>长按图片识别二维码</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </van-popup>
    <van-loading v-show="loading" color="white" class="loading" />
    <img
      v-if="getHostEnvironment() === 'wechat' && isShow"
      :src="resultBase64"
      class="result no-select"
    />
    <div
      v-if="getHostEnvironment() === 'browser' && isShow && !this.loading"
      class="result result-browser"
    >
      <span>长按图片，保存至手机，方便分享和再次浏览 </span>
      <img :src="resultBase64" />
    </div>
  </div>
</template>

<script>
import QRCode from 'qrcode';
import html2canvas from '@/utils/html2canvas.esm';
import {
  formatImgForCanvas,
  getScrollY,
  getHostEnvironment
} from '@/utils/util';
import shareCardMixin from '@/mixins/shareCardMixin';
import tagHaitao from '@/assets/promotion/haitao/tag-haitao2713.png';
import tagDapai from '@/assets/promotion/dapaiqingcang/icon_dapai_58x16@2x.png';
import defaultImg from '@/assets/poster/defaultImg.png';

export default {
  filters: {
    sliceHandle(value = '', length) {
      if (!value) {
        return '';
      }
      const arr = [...value];
      if (arr.length > length) {
        return arr.slice(0, length).join('') + '...';
      }
      return value;
    }
  },
  mixins: [shareCardMixin],
  props: {
    shareObj: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      loading: false,
      qrcode: null,
      isShow: false,
      resultBase64: null,
      shareFloorImgUrl: '',
      forwarderShopLogoUrl: '',
      bannerArr: [],
      icon: {
        tagHaitao,
        tagDapai
      },
      defaultImg,
      timeId: null,
      retryTotal: 0,
      maxRetryTotal: 20 // 最大重试次数
    };
  },
  computed: {
    shopName() {
      let { shopName } = this.shareObj;
      if (shopName && shopName.length > 15) {
        shopName = `${shopName.slice(0, 15)}...`;
      }
      return shopName;
    },
    overseaType() {
      const { overseaType } = this.shareObj;
      let str = '';
      switch (overseaType) {
        case '1':
          str = '海外直邮';
          break;
        case '2':
          str = '保税仓发货';
          break;
        default:
      }
      return str;
    }
  },
  watch: {
    // shareObj(newVal) {
    //   console.log('watch=====', newVal);
    //   if (newVal && newVal.shareFloorImgUrl && newVal.link) {
    //     this.create();
    //   }
    // },
    isShow(newVal) {
      if (!newVal) {
        this.loading = false;
        this.resultBase64 = null;
      } else {
        this.loading = true;
        this.create();
      }
    }
  },
  beforeDestroy() {
    this.initData();
  },
  deactivated() {
    this.initData();
  },
  beforeRouteLeave() {
    this.initData();
  },
  methods: {
    getHostEnvironment,
    async create() {
      console.log('create=====');
      this.resetZoom();
      const {
        forwarder = {},
        shareFloorImgUrl,
        shareFloorImgWidth,
        shareFloorImgHeight
      } = this.shareObj;

      Promise.all([
        formatImgForCanvas(
          shareFloorImgUrl,
          +shareFloorImgWidth,
          +shareFloorImgHeight
        ),
        formatImgForCanvas(forwarder.forwarderShopLogoUrl, 60, 60)
      ])
        .then(([img1, img2]) => {
          this.shareFloorImgUrl = img1;
          this.forwarderShopLogoUrl = img2;
        })
        // eslint-disable-next-line arrow-body-style
        .then(() => {
          return QRCode.toDataURL(this.shareObj.link, { margin: 1 }).then(
            url => {
              this.qrcode = url;
              this.$nextTick(() => {
                try {
                  clearInterval(this.timeId);
                  this.timeId = setInterval(() => {
                    this.retryTotal += 1;
                    if (this.retryTotal >= this.maxRetryTotal) {
                      clearInterval(this.timeId);
                      this.retryTotal = 0;
                    } else if (this.completeHandle()) {
                      clearInterval(this.timeId);
                      this.retryTotal = 0;
                      this.createImg();
                    }
                  }, 200);
                } catch (err) {
                  clearInterval(this.timeId);
                  console.error(err);
                  this.$toast('海报加载失败，请稍后重试！');
                  this.close();
                }
              });
            }
          );
        })
        .catch(e => {
          console.error(e);
          this.$toast('海报加载失败，请稍后重试！');
        });
    },
    createImg() {
      const source = document.getElementById('share-productV2');
      if (!source) return;
      const rect = source.getBoundingClientRect();
      const coptDom = source.cloneNode(true);
      coptDom.style.zIndex = -1;
      coptDom.style.width = `${rect.width}px`;
      coptDom.style.height = `${rect.height}px`;
      document.body.appendChild(coptDom);

      // 适配iOS 13, 12 及以下 && 安卓
      const scrollY = getScrollY();

      html2canvas(coptDom, {
        allowTaint: true,
        useCORS: true,
        logger: true,
        x: rect.left,
        y: rect.top + scrollY,
        scale: 1.6
      })
        .then(canvas => {
          const imgUri = canvas.toDataURL();
          this.resultBase64 = imgUri;
          this.loading = false;
          document.body.removeChild(coptDom);
        })
        .catch(err => {
          console.log(err);
          this.loading = false;
          document.body.removeChild(coptDom);
          this.$toast('海报加载失败，请稍后重试！');
        });
    },
    completeHandle() {
      const div = document.getElementById('share-productV2');
      if (!div) {
        return false;
      }

      const imgArr = div.querySelectorAll('.poster-img') || [];
      return Array.prototype.slice
        .call(imgArr)
        .every(img => img.complete && img.naturalWidth);
    },
    initData() {
      clearInterval(this.timeId);
      this.timeId = null;
      this.retryTotal = 0;
      this.maxRetryTotal = 20;
    }
  }
};
</script>

<style scoped>
.van-popup {
  position: fixed;
  top: 50%;
  left: 50%;
  background-color: transparent;
  z-index: 9999;
}

.bg-transparent {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}
</style>

<style lang="scss" scoped>
.share-wrapper {
  width: 375px;
  // height: 667px;
  position: relative;
}
#share-productV2 {
  width: 375px;
  top: 50%;
  left: 50%;
  background: #fff;
  transform: translate(-50%, -50%);
  position: fixed;
  box-sizing: border-box;
  font-family: PingFangSC-Regular, PingFang SC;
  .banner {
    width: 100%;
    position: relative;
    .goods_info_bg {
      width: 100%;
      height: 40px;
      position: absolute;
      left: 0;
      bottom: -40px;
      img {
        width: 100%;
      }
    }
    .goods-info {
      position: relative;
      .goods-meta-wrap {
        position: absolute;
        z-index: 100;
        display: flex;
        align-items: center;
        box-sizing: border-box;
        .goods-meta {
          display: flex;
          // flex-direction: column;
          font-size: 10px;
          color: rgba(255, 16, 16, 1);
          flex-wrap: wrap;
          word-break: break-all;
          span {
            display: inline-block;
            // min-width: 36px;
            padding: 2px 4px;
            background-color: rgba(255, 238, 240, 1);
            text-align: center;
            margin-right: 4px;
            border-radius: 2px;
          }
        }
      }
      img {
        width: 100%;
      }
    }
    .activity-info {
      padding: 0 20px;
      display: flex;
      > span {
        width: 60px;
        height: 22px;
        padding-right: 6px;
        &.activity-label2 {
          width: 36px;
        }
        img {
          width: 100%;
        }
      }
      p {
        height: 22px;
        border-radius: 100px;
        display: flex;
        font-size: 12px;
        color: rgba(255, 16, 20, 1);
        line-height: 22px;
        span {
          padding: 0 13px 0 6px;
          background-color: rgba(255, 238, 240, 1);
          border-top-right-radius: 100px;
          border-bottom-right-radius: 100px;
        }
        img {
          height: 100%;
        }
      }
      .yugao {
        background-color: rgba(255, 246, 238, 1);
        color: rgba(255, 134, 37, 1);
      }
      .jingxingzhong {
        width: 100%;
        display: flex;
        justify-content: space-between;
        color: rgba(153, 153, 153, 1);
        span {
          background-color: transparent;
        }
      }
    }
  }
  .shop-wrap {
    width: 100%;
    padding: 30px 20px 20px;
    display: flex;
    justify-content: space-between;
    box-sizing: border-box;
    .left-box {
      display: flex;
      flex: 1;
      flex-direction: column;
      justify-content: inherit;
      padding-top: 11px;
      .shop-info {
        display: flex;
        align-items: center;
        .shop-logo {
          width: 60px;
          height: 60px;
          overflow: hidden;
          border-radius: 60px;
          box-sizing: border-box;
          img {
            width: 60px;
            height: 60px;
            border-radius: 60px;
            object-fit: cover;
          }
        }
        .shop-desc {
          display: flex;
          max-width: 144px;
          flex-direction: column;
          color: rgba(102, 102, 102, 1);
          padding-left: 8px;
          // margin-top:-10px;
          font-size: 12px;
          span {
            line-height: 16px;
            &:nth-child(2) {
              padding: 3px 0 6px;
              font-weight: 600;
              font-size: 14px;
              color: rgba(51, 51, 51, 1);
            }
            &:nth-child(3) {
              line-height: 12px;
            }
          }
        }
      }
      .shop-meta {
        font-size: 10px;
        color: rgba(102, 102, 102, 1);
        display: flex;
        span {
          position: relative;
          padding-right: 10px;
          display: flex;
          i {
            width: 12px;
            height: 12px;
            margin-right: 5px;
            &:last-child {
              margin: 0;
            }
            img {
              width: 100%;
            }
          }
          em {
            font-style: normal;
          }
        }
      }
    }
    .shop-link {
      display: flex;
      // flex: 1;
      flex-direction: column;
      align-items: center;
      justify-content: inherit;
      min-width: 90px;
      img {
        margin-top: 10px;
      }
      .qrcode {
        width: 80px;
        height: 80px;
      }
      .qrcode-tip {
        padding-top: 9px;
        font-size: 10px;
        color: rgba(102, 102, 102, 1);
        line-height: 14px;
      }
    }
  }
}
.loading {
  z-index: 9999;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.result {
  top: 50%;
  left: 50%;
  position: fixed;
  max-width: 80%;
  max-height: 86%;
  transform: translate(-50%, -50%);
  z-index: 9999;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  span {
    color: #ffffff;
    font-size: 14px;
    margin-bottom: 8px;
  }
  &.no-select {
    -webkit-touch-callout: none; /*系统默认菜单被禁用*/
    user-select: none; //文本不能被选择
  }
  img {
    border-radius: 8px;
    height: 100%;
  }
}

.result-browser {
  width: 80%;

  img {
    width: 100%;
  }
}
</style>
